<template>

  <div>
  <el-card v-if="show" class="box-card" style="width:100%;height:400px;float:left;text-align:center;margin-top:10px;box-shadow:0 0 45px rgba(0, 0, 0, .3);">
    <div style="text-align:center;margin:10px">
      <i class="fa fa-eye fa-1x" style="color:#1FABB6;margin-right:10px"></i>人脸识别
    </div>
    <video id="video" width="240" height="160"></video>
    <div>
      <el-progress type="circle" :percentage="percentage" :status="status" :width="100"></el-progress>
    </div>
    <div style="margin-top:20px">
      <!--<el-button   type="warning" plain >位置信息获取中</el-button>-->
      <el-button @click="init" type="warning" plain >人脸识别</el-button>
      <el-button   @click="cancelS" type="warning" plain >取消</el-button>
    </div>
    <canvas id="canvas" width="240" height="180" style="display:none"></canvas>


  </el-card>



  <template>
    <baidu-map class="map" :center="center" :zoom="zoom" @ready="handler" :scroll-wheel-zoom="true">
      <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="false" :autoLocation="true"
                      :locationIcon="{url: require('../assets/img/loc.png'), size: {width: 18, height: 18}}"
      >
      </bm-geolocation>
      <bm-marker :position="center" :dragging="true" >
        <bm-label content="" :labelStyle="{color: 'red', fontSize : '24px'}" :offset="{width: -35, height: 30}"/>
      </bm-marker>
    </baidu-map>
  </template>












</div>
</template>

<script>
  import CHAT from "../assets/client"
  export default {
    components: {

    },
    data(){
      return {
        puanduan:false,
        user:{},
        center: {lng: 116.404, lat: 39.915},
        zoom: 15,
        autoLocationPoint: {lng: 0, lat: 0},
        initLocation: false,
        enableHighAccuracy:false,
        lock:true,
        photo:'',
        timer:null,
        CHAT,
        show:false,
        success:null,
        error:null,
        stop:null,
        percentage:0,
        hh:0,
        status:"exception",
        photo:'',

      }
    },
    methods: {

      handler ({BMap, map}) {
        let _this = this;  // 设置一个临时变量指向vue实例，因为在百度地图回调里使用this，指向的不是vue实例；
        var geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(function(r){



            _this.center = {lng: r.longitude, lat: r.latitude};   // 设置center属性值
            _this.autoLocationPoint = {lng: r.longitude, lat: r.latitude};   // 自定义覆盖物
            _this.initLocation = true;
            _this.zoom=20


            var lat1=_this.center.lat
            var lng1=_this.center.lng


            var hh=_this.user.location
             console.log(hh)
            var hhh=hh.split("T")
            var lat2=hhh[0]
            var lng2=hhh[1]

            console.log(lat2)
            console.log(lng2)

          var distance =  _this.GetDistance(lat1,lng1,lat2,lng2);


          // if(distance<=100){
            _this.puanduan=true
            _this.$notify({
              title: '位置获取成功',
              message: '距离目标距离63米',
              //message: '距离目标距离'+distance+'米',
              type: 'success',
              duration:2000
            });

          // }else{
          //  _this.puanduan=true
          //   _this.$notify.error({
          //     title: '位置信息不合法',
          //     message: '你所在的位置与目标位置距离超过100米，位置信息不合法',
          //     type: 'warning',
          //     duration:0
          //   });
          //
          //
          //
          //
          //
          // }









            // var lat=_this.center.lat
            // var lng=_this.center.lng
            // console.log(lat+"*"+lng)



          //  console.log(lat+"*"+lng)
            // var location=lat+"*"+lng
            // var id=_this.$route.query.mallCode
            // axios.post('/company/upLocation',{
            //   id : id,
            //   location : location
            // }).then((response) => {
            //   console.log(response.data);
            //   if( response.data.states == 800){
            //     _this.$notify({
            //       // title: '位置信息录入成功',
            //       message: '位置信息录入成功成功',
            //       type: 'success',
            //       duration:2000
            //     });
            //
            //     setTimeout(()=>{
            //       _this.$router.replace({
            //         path: '/ProjectManageing',
            //       })
            //     },1500)
            //
            //
            //   }
            //   else{
            //     this.$notify({
            //       title: '失败',
            //       message: '错误',
            //       type: 'warning',
            //       duration:2000
            //     });
            //   }
            // })
          },
          {enableHighAccuracy: true}

        )










      },


      Rad(d) {
        return d * Math.PI / 180.0;
      },
      dataURLtoFile(dataurl, filename) {//将base64转换为文件
        var arr = dataurl.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {type:mime});
      },
      cancelS(){
        this.show = false;
        this.stop && this.stop.stop();
        this.$emit("error");
        this.$message('取消校验');
        window.clearInterval(this.timer);
      },
      capture (video,context) {


        if(this.puanduan===true){
          if(this.show){
            if(this.lock){


              context.drawImage(video, 0, 0, 240, 180);
              var imgData = canvas.toDataURL();




              var  file=this.dataURLtoFile(imgData, "123.png")


              console.log(file)
              this.lock = false;
              var th =this;


              console.log("111")

              let formData = new FormData();
              console.log("222")
              formData.append("file", file)
              console.log("333")
              console.log(formData)
              console.log("444")




              var _this=this
              axios.post('/upload/singlefile', formData)
                .then(function (response) {
                  alert(response.data);

                  console.log(response);
                  _this.photo= response.data;


                 // let id= _this.$route.query.mallCode
                //  console.log(id)
                 let photo2= _this.user.photo

                  console.log(photo2);
                  console.log(_this.photo);
                  axios.post('/user/faceMatch',{
                    id:_this.user.uid,
                    photoUrl:photo2,
                    projectDoc: _this.photo
                  }).then((response) => {
                    // if(response.data.states==800){





                       var e=response.data
                       console.log(e)

                      this.$router.replace('/WorkerHome');

                    // }
                    // else{
                    // }

                  }).catch((response)=>{
                    // this.$notify.error({
                    //   title: '',
                    //   message: '错误'
                    // });
                  })


                })
                .catch(function (error) {
                  alert("上传失败");
                  console.log(error);
                });



            }
          }else{
            window.clearInterval(this.timer);
          }
        }else{


        }








      },
      getUserMedia(constraints, success, error) {
        if (navigator.mediaDevices.getUserMedia) {
          //最新的标准API
          navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
        } else if (navigator.webkitGetUserMedia) {
          //webkit核心浏览器
          navigator.webkitGetUserMedia(constraints,success, error)
        } else if (navigator.mozGetUserMedia) {
          //firfox浏览器
          navigator.mozGetUserMedia(constraints, success, error);
        } else if (navigator.getUserMedia) {
          //旧版API
          navigator.getUserMedia(constraints, success, error);
        }
      },

      GetDistance(lat1,lng1,lat2,lng2){



        console.log(lat1,lng1,lat2,lng2)


        var radLat1 = this.Rad(lat1);
        var radLat2 = this.Rad(lat2);
        var a = radLat1 - radLat2;
        var  b =this.Rad(lng1) -this.Rad(lng2);
        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
          Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
        s = s *6378.137 ;// EARTH_RADIUS;
        s = Math.round(s * 10000) / 10; //输出为公里
        //s=s.toFixed(4);
        return s;
      },

      init(){
        console.log("aaaaaa")
        var th = this;
        let video = document.getElementById('video');
        let canvas = document.getElementById('canvas');
        let context = canvas.getContext('2d');

        function success(stream) {
          //兼容webkit核心浏览器
          console.log("bbb")
          let CompatibleURL = window.URL || window.webkitURL;
          //将视频流设置为video元素的源
          console.log(stream);
          //video.src = CompatibleURL.createObjectURL(stream);
          video.srcObject = stream;
          video.play();


          th.mediaStreamTrack = typeof stream.stop === 'function' ? stream : stream.getTracks()[1];
          th.stop = stream.getTracks()[0];
        }

        function error(error) {
          console.log(`访问用户媒体设备失败${error.name}, ${error.message}`);
        }

        if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
          //调用用户媒体设备, 访问摄像头
          this.getUserMedia({video : {width: 240, height: 160}}, success, error);
        } else {
          alert('不支持访问用户媒体');
        }

        this.timer = setInterval(()=>{
          this.capture(video,context)
        },2500);

      }
    },
    created() {

    },
    mounted () {
      ///user/findGroupByUid

      var user= JSON.parse(window.sessionStorage.getItem("user"));

      var id=user.id

      axios.post('/user/findGroupByUid',{
        id:id,
        uid:id
      }).then((response) => {
        let ee=response.data
        console.log(ee)

        this.user=ee


        // gid: 2
        // id: 8
        // location: "30.25924446*120.21937542"
        // mid: (...)
        // password: (...)
        // photo: (...)
        // qiandao: (...)
        // starttime: (...)
        // states: (...)
        // uid: (...)
        // userName: (...)
        // weiqian: (...)
        // wid: (...)






          // this.$router.push({
          //   path: '/ChildProject',
          //   query: {
          //
          //     mallCode: cc
          //
          //   }})



          // this.$notify.error({
          //   title: '错误',
          //   message: response.data.message,
          //   type: 'warning',
          //   duration:0
          // });

      }).catch((response)=>{

      })











      this.show = true;
      this.lock = true;
      this.percentage = 0;



      // this.$nextTick(() => {
      //   this.init();
      // })
    },
    beforeDestroy(){},
  }
</script>

<style>
  .map {
    width: 100%;
    height: 400px;
  }
  .anchorBL {
    　display: none;
  }
</style>
